using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.Text;
using System.Xml.Serialization;
using Microsoft.TeamFoundation.Client;
using Microsoft.TeamFoundation.Framework.Client;
using Microsoft.TeamFoundation.Framework.Common;
using Microsoft.TeamFoundation.Server;
using Microsoft.TeamFoundation.WorkItemTracking.Client;
using PowersourceUIToolkit;

namespace UCL.Powersource.TFS
{
    [DataContract(IsReference = true)]
    public class TfsTeamProjectConfiguration : PropertyChangedInitializedLifeCycle, ITfsTeamProjectConfiguration, ILabel
    {
        //public Guid TeamProjectConfiguration_Guid {get;set;}
        [DataMember]
        public string UniqueName { get; private set; }//Unique name of the tfs project
        [DataMember]
        public int UniqueId { get; private set; } //Unique id of the tfs project
        [DataMember]
        public bool IsChosen { get; set; }  //Tfs project chosen
        [DataMember]
        public Guid UniqueGuid { get; private set; }
        [DataMember]
        public string SolutionFilePath { get; set; }

        public bool IsValidForStatistic
        {
            get { return IsChosen; }
        }

        public string Label { get { return UniqueName; } }

        [DataMember]
        public ITfsTeamProjectCollectionConfiguration TeamProjectCollectionConfiguration { get; private set; }

        public IEnumerable<ITimeFrame> ProjectTimeframes
        {
            get { return TeamProjectCollectionConfiguration.ProjectCollectionTimeFrames; }
        }

        /// <summary>
        /// tfs stat project configurartion, which includes: unique name and id of the project
        /// </summary>
        /// <param name="UniqueName">Unique name of the tfs project</param>
        /// <param name="UniqueId">Unique id of the tfs project</param>
        public TfsTeamProjectConfiguration(string UniqueName, int UniqueId, ITfsTeamProjectCollectionConfiguration TeamProjCollConf)
        {
            this.UniqueName = UniqueName;
            this.UniqueId = UniqueId;
            this.TeamProjectCollectionConfiguration = TeamProjCollConf;
            this.UniqueGuid = Guid.NewGuid();
            InitializeBridge();
        }

        public ILog Log = LogManager.GetLog(typeof(TfsTeamProjectConfiguration));

        protected override bool OnInitializing()
        {

            Log = LogManager.GetLog(typeof(TfsTeamProjectConfiguration));
            InitializeBridge();
            return (Log != null && _ProjectAnalysisBridge != null);
        }
        protected override void OnDisposing()
        {
            if (ProjectAnalysisBridge != null)
            {
                ProjectAnalysisBridge.Dispose();
            }
            return;
        }

        private void InitializeBridge()
        {
            if (_ProjectAnalysisBridge == null)
            {
                var abtype = IoC.GetDefaultInterfaceImplementationType(typeof(IAnalysisBridge)); ;
                if (abtype != null)
                {
                    _ProjectAnalysisBridge = (IAnalysisBridge)Activator.CreateInstance(abtype, this);
                }
                else
                {
                    _ProjectAnalysisBridge = new AnalysisBridge(this);
                }
                _ProjectAnalysisBridge.Initialize();

            }
        }

        [DataMember]
        private IAnalysisBridge _ProjectAnalysisBridge;

        public IAnalysisBridge ProjectAnalysisBridge
        {
            get { return _ProjectAnalysisBridge; }
        }

        [DataMember]
        private string _Uri;

        public string Uri
        {
            get
            {
                return _Uri;
            }
            internal set
            {
                _Uri = value;
            }
        }

        private List<string> _MemberNames;

        public string MemberNamesString
        {
            get
            {

                if (MemberNames != null)
                {
                    var str = new StringBuilder();
                    for (int i = 0; i < MemberNames.Count; i++)
                    {
                        if (i != 0) str.Append(", ");

                        str.Append(MemberNames[i]);
                    }

                    return str.ToString();
                }

                return "No Members Attached";
            }
        }

        public IReadOnlyList<string> MemberNames
        {
            get { return _MemberNames; }
        }

        public void Synchronize()
        {
            SynchronizeMembers();
        }

        private void SynchronizeMembers()
        {
            _MemberNames = new List<string>();

            var tpc = IoC.Get<ITfsTeamProjectCollectionFactory>().GetTeamProjectCollection(new Uri(TeamProjectCollectionConfiguration.Uri));
            var ser = tpc.GetService<TfsTeamService>();
            var smt = ser.QueryTeams(Uri);

            foreach (TeamFoundationTeam team in smt)
            {
                var members = team.GetMembers(((TfsTeamProjectCollectionAdapter)tpc).TfsTeamProjectCollection, MembershipQuery.Direct);
                foreach (var member in members)
                {
                    if (!_MemberNames.Contains(member.DisplayName))
                        _MemberNames.Add(member.DisplayName);
                }
            }
        }


    }
}
